package com.lhn.case3;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.client.ZKClientConfig;

/**
 * 〈一句话功能简述>
 * 〈〉
 *
 * @Author 17505
 * @Create 2022/3/12
 * @Since 1.0.0
 */
public class CuratorLockTest {


    public static void main(String[] args) throws Exception {
        // 创建分布式锁1
        InterProcessMutex locks1 = new InterProcessMutex(getCuratorFramework(), "/locks");

        // 创建分布式锁2
        InterProcessMutex locks2 = new InterProcessMutex(getCuratorFramework(), "/locks");

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // 获取到锁
                    locks1.acquire();
                    System.out.println("线程 1 获取到锁了！");
                    locks1.acquire();
                    System.out.println("线程 1 再次获取到锁了！");
                    System.out.println("休息一下！");
                    Thread.sleep(5 * 1000);
                    locks1.release();
                    System.out.println("线程 1 释放锁了！");
                    locks1.release();
                    System.out.println("线程 1 释放锁了！");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // 获取到锁
                    locks2.acquire();
                    System.out.println("线程 2 获取到锁了！");
                    locks2.acquire();
                    System.out.println("线程 2 再次获取到锁了！");
                    System.out.println("休息一下！");
                    Thread.sleep(5 * 1000);
                    locks2.release();
                    System.out.println("线程 2 释放锁了！");
                    locks2.release();
                    System.out.println("线程 2 释放锁了！");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private static CuratorFramework getCuratorFramework() throws Exception {
        ExponentialBackoffRetry backoffRetry = new ExponentialBackoffRetry(3000, 3);
        DefaultZookeeperFactory zookeeperFactory = new DefaultZookeeperFactory();
        CuratorFramework client = CuratorFrameworkFactory.builder().connectString("192.168.3.33:2181")
                .sessionTimeoutMs(2000).retryPolicy(backoffRetry).
                        zookeeperFactory(zookeeperFactory).build();
        client.start();
        System.out.println("客户端启动成功！");
        return client;
    }

}